import * as process from "process"
import { NestFactory } from "@nestjs/core"
import { AppModule } from "../module"
import * as fs from "fs"
import * as dotenv from "dotenv"
import { NestExpressApplication } from "@nestjs/platform-express"
import { join } from "path"
import { NextFunction, Request, Response } from "express"
// Load environment variables
dotenv.config()
const isProductionEnv = () => {
  return process.env["OPERATING_ENV"] === "prod"
}
const useOrigin = () => {
  if (isProductionEnv()) {
    return "https://" + process.env["FRONT_DOMAIN"];
  }
  return "http://localhost:5173"
}
const httpsOptions = {
  key: fs.readFileSync("public/ssl/ssl.key"),
  cert: fs.readFileSync("public/ssl/ssl.pem")
}

export const appConfig = {
  corsOptions: {
    origin: useOrigin(),
    credentials: true,
    methods: "GET, POST"
  },
  globalPrefix: "/api",
  port: 3000,
  useApp: async () => {
    if (isProductionEnv()) {
      return NestFactory.create<NestExpressApplication>(AppModule, {
        httpsOptions
      });
    }
    return NestFactory.create<NestExpressApplication>(AppModule);
  },
  staticPath: join(process.cwd(), "public", "uploads"),
  globalMiddleware: (req: Request, res: Response, next: NextFunction) => {
    next();
  }
}
